//
//  UIImage+category.m
//  jobClient
//
//  Created by 一览ios on 16/10/17.
//  Copyright © 2016年 YL1001. All rights reserved.
//

#import "UIImage+category.h"

#import "UILabel+EL.h"
#import <Accelerate/Accelerate.h>

@implementation UIImage (category)

#pragma mark - 纯色图片
+ (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark - 视图转图片
+ (UIImage *)imageWithView:(UIView *)view {
    if (!view) {
        return nil;
    }
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - Label转Image
+ (UIImage *)imageWithLabelText:(NSString *)text font:(UIFont *)font backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor cornerRadius:(CGFloat)cornerRadius height:(CGFloat)height {
    if (StringIsEmpty(text)) return nil;
    
    CGFloat width = ceil([UILabel flexibleWidthWithText:text font:font height:height lineSpacing:0] + 4);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectIntegral(CGRectMake(0, 0, width, ceil(height)))];
    
    if (cornerRadius > 0) {
        label.layer.cornerRadius = cornerRadius;
        label.layer.masksToBounds = YES;
    }
    label.backgroundColor = backgroundColor;
    label.textColor = textColor;
    label.text = text;
    label.font = font;
    label.textAlignment = NSTextAlignmentCenter;
    return [self imageWithView:label];
}

+ (UIImage *)imageWithLabelText:(NSString *)text font:(UIFont *)font backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth cornerRadius:(CGFloat)cornerRadius height:(CGFloat)height {
    if (StringIsEmpty(text)) return nil;
    
    CGFloat width = ceil([UILabel flexibleWidthWithText:text font:font height:height lineSpacing:0] + 4);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectIntegral(CGRectMake(0, 0, width, ceil(height)))];
    
    if (cornerRadius > 0) {
        label.layer.cornerRadius = cornerRadius;
        label.layer.masksToBounds = YES;
    }
    label.backgroundColor = backgroundColor;
    label.textColor = textColor;
    label.text = text;
    label.font = font;
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.borderColor = borderColor.CGColor;
    label.layer.borderWidth = borderWidth;
    return [self imageWithView:label];
}

#pragma mark - 图片高斯模糊处理
/**
 @param image 输入图片
 @param blur 模糊度
 @return 输出图片
 */
+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur
{
    if ((blur < 0.0f) || (blur > 1.0f)) {
        blur = 0.5f;
    }
    
    int boxSize = (int)(blur * 100);
    boxSize -= (boxSize % 2) + 1;
    
    CGImageRef img = image.CGImage;
    
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    void *pixelBuffer;
    
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL,
                                       0, 0, boxSize, boxSize, NULL,
                                       kvImageEdgeExtend);
    
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(
                                             outBuffer.data,
                                             outBuffer.width,
                                             outBuffer.height,
                                             8,
                                             outBuffer.rowBytes,
                                             colorSpace,
                                             CGImageGetBitmapInfo(image.CGImage));
    
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    
    free(pixelBuffer);
    CFRelease(inBitmapData);
    
    CGImageRelease(imageRef);
    
    return returnImage;
}

+ (UIImage *)blurryWithView:(UIView *)view blurLevel:(CGFloat)blur {
    UIImage *blurImage = [self imageWithView:view];
    if(!blurImage){
        return nil;
    }
    return [self blurryImage:blurImage withBlurLevel:blur];
}

- (UIImage *)blurryWithBlurLevel:(CGFloat)blur {
    return [[self class] blurryImage:self withBlurLevel:blur];
}


#pragma mark - 压缩图片大小（压缩质量）
- (NSData *)compressQualityWithMaxLength:(NSInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    if (data.length < maxLength) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(self, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}

/** * 压缩图片到指定文件大小
 *
 * @param image 目标图片
 * @param size 目标大小(最大值)
 *
 * @return 返回的图片文件
 */
- (NSData *)compressToMaxDataSizeKBytes:(CGFloat)size {
    NSData * data = UIImageJPEGRepresentation(self, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(self, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        } else {
            lastData = dataKBytes;
        }
    }
    return data;
}

@end
